import React from 'react';
import {Form, Row, Col, Input, Radio, Icon, Upload} from 'antd';
const FormItem = Form.Item;
const RadioGroup = Radio.Group;

let BaseInfo = React.createClass({
    getInitialState() {
        return {
            key:[],
            count: 0,
            cardList: [],
            renterFrontPic: [], //固定承租人 身份证正面
            renterBackPic: [],  //固定承租人 身份证反面
            otherRenterInfo: [], // 其他承租人信息
        }
    },
    componentWillReceiveProps(nextProps) {
        if(nextProps.flag === 'modify') {
            this.setState({
                renterFrontPic: nextProps.renterFrontPic,
                renterBackPic: nextProps.renterBackPic,
                otherRenterInfo: nextProps.otherRenterInfo,
            });
            this.setStates(nextProps.otherRenterInfo);
        }
        
    },
    // 设置 states
    setStates(data) {
        data.forEach((item, t) => {
            let obj = {};
            obj[`renterFrontPic${t}`] = item.renterFrontPic;
            obj[`renterBackPic${t}`] = item.renterBackPic;
            this.setState(obj)
        });
        
    },
    componentWillUnmount(){ 
        localStorage.renterFrontPic = null;
        localStorage.renterBackPic = null;
    },
    // 新增一行
    addRecord() {
        let {key, count} = this.state;
        key.push(++count)
        key.forEach(t=> {
            localStorage[`renterFrontPic${t}`] = JSON.stringify([]);
            localStorage[`renterBackPic${t}`] = JSON.stringify([]);
            let obj = {};
            obj[`renterFrontPic${t}`] = JSON.stringify([]);
            obj[`renterBackPic${t}`] = JSON.stringify([]);
            this.setState(obj)
        });
        
        this.setState({
            key: key,
            count: count
        });
    },
    deleteRecord(index) {
        let {key} = this.state;
        key = key.filter((t) => {
            return t !== index
        });
        // 清除对应localstorage
        key.forEach(t=> { 
            localStorage.removeItem(`renterFrontPic${t}`);
            localStorage.removeItem(`renterBackPic${t}`);
            let obj = {};
            obj[`renterFrontPic${t}`] = JSON.stringify([]);
            obj[`renterBackPic${t}`] = JSON.stringify([]);
            this.setState(obj)
        });
        
        this.setState({
            key: key,
        });
    },
    deleteOtherRecord(index) {
        let {otherRenterInfo} = this.state;
        otherRenterInfo = otherRenterInfo.filter((item, i) => {
            return i !== index
        });
        // 清除对应localstorage
        otherRenterInfo.forEach((item, i)=> { 
            localStorage.removeItem(`renterFrontPic${i}`);
            localStorage.removeItem(`renterBackPic${i}`);
            let obj = {};
            obj[`renterFrontPic${i}`] = JSON.stringify([]);
            obj[`renterBackPic${i}`] = JSON.stringify([]);
            this.setState(obj)
        });
        
        this.setState({
            otherRenterInfo: otherRenterInfo,
        });
        // 更新父组件
        this.props.updateState({
            otherRenterInfo: otherRenterInfo,
        });
    },
    // 更新状态
    updateStates(states) {
        this.setState(states)
    },
    // 图片显示参数重构
    resetImgUrl(imgArry) {
        //console.log(imgArry,imgArry.length);
        if(imgArry.length > 0) {
            imgArry.forEach((item) => {
                let length = item.url.split('/').length;
                let id = item.url.split('/')[length-1].split('.')[0];

                let imgMaps = {
                    uid: id,
                    type: item.type,
                    status: 'done',
                    url: Utils.apiServer + item.url,
                    thumbUrl: Utils.apiServer + item.url,
                };
                if (item.type == 'card') {
                    let curKey = parseInt(item.flag.replace(/[^0-9]+/g, '')); // 获取flag里的数字标记
    　　　　       let keyName =item.flag.replace(/[^a-zA-Z]+/g, ''); // 获取 flag里的字段名称
                    
                    if(item.flag === 'renterFrontPic'){
                        
                        let renterFrontPic = JSON.parse(localStorage.renterFrontPic) || this.state.renterFrontPic;
                        renterFrontPic.push(imgMaps)
                        //console.log('renterFrontPic',renterFrontPic)
                        localStorage.renterFrontPic = JSON.stringify(renterFrontPic);
                        this.setState({
                            renterFrontPic: renterFrontPic
                        });
                    }else if(item.flag === 'renterBackPic'){
                        let renterBackPic = JSON.parse(localStorage.renterBackPic) || this.state.renterBackPic;
                        renterBackPic.push(imgMaps)
                        //console.log('renterBackPic',renterBackPic)
                        localStorage.renterBackPic = JSON.stringify(renterBackPic);
                        this.setState({
                            renterBackPic: renterBackPic
                        });
                    }
                    if(!isNaN(curKey)){
                        let arry = [];
                        arry.push(imgMaps)
                        localStorage[item.flag] = JSON.stringify(arry);
                        let obj = {};
                        obj[item.flag] = arry;
                        this.setState(obj); 
                    }
                    
                }
            })
       } 
    },
    // 删除图片
    deleteImg(params) {
    //    //console.log(params)
       params.forEach((item) => {
           
           if (item.type == 'card') {
               let curKey = parseInt(item.flag.replace(/[^0-9]+/g, '')); // 获取flag里的数字标记
  　　　　      let keyName =item.flag.replace(/[^a-zA-Z]+/g, ''); // 获取 flag里的字段名称
                if(item.flag === 'renterFrontPic'){
                    
                    let renterFrontPic = JSON.parse(localStorage.renterFrontPic);
                    renterFrontPic = renterFrontPic.filter(t=> {
                        //console.log('=====',t.uid!==item.file.uid);
                        return t.uid !== item.file.uid
                    })
                    localStorage.renterFrontPic = JSON.stringify(renterFrontPic);
                    this.setState({
                        renterFrontPic: renterFrontPic
                    });
                }else if(item.flag === 'renterBackPic'){
                    let renterBackPic = JSON.parse(localStorage.renterBackPic);
                    renterBackPic = renterBackPic.filter(t=> {
                        return t.uid !== item.file.uid
                    })
                    localStorage.renterBackPic = JSON.stringify(renterBackPic);
                    this.setState({
                        renterBackPic: renterBackPic
                    });
                }
                if(!isNaN(curKey)){
                    let arry = [];
                    arry = JSON.parse(localStorage[item.flag]).filter(t=> {
                        return t.uid !== item.file.uid
                    })
                    
                    localStorage[item.flag] = JSON.stringify(arry);
                    //console.log('localStorage-------------------',localStorage);
                    let obj = {};
                    obj[item.flag] = arry;
                    this.setState(obj); 
                }
           }
       })
    },
    getCardProps (cardState, type, flag) {
        return {
            name: 'file',
            data: {nid: `${type}`},
            listType: 'picture-card',
            action: Utils.apiServer + '/img/uploadifySave',
            multiple: true,
            fileList: cardState || [],
            beforeUpload(file) {
                const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
                const isSize = file.size > 5242880 ? false : true;
                if (!isJPG) {
                Message.error('只能上传jpg、png图片文件哦！', 10);
                return isJPG
                }
                if (!isSize) {
                Message.error('你选择的图片过大！', 10);
                return isSize
                }
            },
            onChange: (files) => {
                let status = files.file.status;
                if (status == 'done') {
                    let file = files.file;
                    let imgArry = file.response ? file.response.data : [];
                    let imgArryNew = [];
                    imgArry.forEach( t=> {
                        let obj = {
                            type: `${type}`,
                            flag: `${flag}`,
                            url: t
                        }
                        imgArryNew.push(obj)
                        
                    })
                    this.resetImgUrl(imgArryNew);
                }
                
            },
            onPreview: (file) => {
                let arry = file.url.split('.')
               
            },
            onRemove: (file) => {
                let status = file.status;
                if (status == 'removed') {
                    
                    let imgArry = [file];
                    let imgArryNew = [];
                    // //console.log('imgArry',imgArry);
                    imgArry.forEach( t=> {
                        let obj = {
                            type: `${type}`,
                            flag: `${flag}`,
                            file: t
                        }
                        imgArryNew.push(obj)
                        
                    })
                    this.deleteImg(imgArryNew);
                }
            }
            };
    },
    render () {
        let {key, count, renterFrontPic, renterBackPic, otherRenterInfo} = this.state;
        let { getFieldProps } = this.props.form;
        let {isDisabled, flag} = this.props;
        let path = window.location.hash;
        let lastPath = path.split('/')[path.split('/').length - 1].split('?')[0];
        let fixationVisible = lastPath === 'update' ? true: isDisabled;
      
        let cardFrontProps = this.getCardProps(renterFrontPic,'card', 'renterFrontPic');
        let cardBackProps = this.getCardProps(renterBackPic,'card', 'renterBackPic');
        //console.log('-------------',this.state)
        
        return (
            
            <div className="form-group">
                <h3><span>基本信息</span></h3>
                <Form inline form={this.props.form}>
                <div style={{borderBottom: '1px solid #eee'}}>
                    <Row gutter={24}>
                        <Col sm={8}>
                            <FormItem label="租客姓名">
                            <Input disabled={fixationVisible} {...getFieldProps('renterName', {initialValue: '',
                                rules: [{ required: true,  message: '租客姓名不可为空' }]})} />
                            </FormItem>
                        </Col>
                        <Col sm={8}>
                            <FormItem label="身份证号码">
                            <Input disabled={fixationVisible} {...getFieldProps('renterNo', {initialValue: '',
                                rules: [{ required: true,  message: '身份证号码不可为空' }, {validator: Utils.card}]})} />
                            </FormItem>
                        </Col>
                        <Col sm={8}>
                            <FormItem label="联系号码">
                            <Input disabled={isDisabled} {...getFieldProps('renterPhone', {initialValue: '',
                                rules: [{ required: true,  message: '联系号码不可为空' },
                                {validator: Utils.phone}]})} />
                            </FormItem>
                            {
                                isDisabled?'':
                                <a href="javascript:;" style={{marginRight: 10}} onClick={this.addRecord}><Icon style={{fontSize: 16}} type="plus-circle-o" /></a> 
                            }
                            
                        </Col>
                    </Row>
                    <Row gutter={24}>
                        <Col sm={8}>
                            <FormItem label="租客性别">
                            <RadioGroup disabled={fixationVisible}  {...getFieldProps('renterSex',{initialValue:'男'})}>
                                <Radio value="男">男</Radio>
                                <Radio value="女">女</Radio>
                            </RadioGroup>
                            </FormItem>
                        </Col>
                        <Col sm={8}>
                            <FormItem label="联系地址">
                            <Input disabled={isDisabled} {...getFieldProps('renterAddress')} />
                            </FormItem>
                        </Col>
                        <Col sm={8}>
                            <FormItem label="工作单位">
                            <Input disabled={isDisabled} {...getFieldProps('renterCompany')} />
                            </FormItem>
                        </Col>
                    </Row>
                    <Row gutter={24} className="pic-box">
                        <Col sm={24} className="img-label-wrap">
                            <FormItem
                            label="身份证正面">
                            <Upload  {...cardFrontProps} >
                                {
                                    this.state.renterFrontPic.length === 0 ?
                                            <div className="img-icon">
                                                <Icon type="plus"/>
                                                <h5>添加</h5>
                                            </div>:''
                                }   
                            </Upload>
                            </FormItem>
                        </Col>
                    </Row>
                    <Row gutter={24} className="pic-box">
                        <Col sm={24} className="img-label-wrap">
                            <FormItem
                            label="身份证反面">
                            <Upload  {...cardBackProps} >
                                {
                                    this.state.renterBackPic.length === 0 ?
                                            <div className="img-icon">
                                                <Icon type="plus"/>
                                                <h5>添加</h5>
                                            </div>:''
                                }
                            </Upload>
                            </FormItem>
                        </Col>
                    </Row>
                </div>
                {
                   
                    otherRenterInfo.map((item, t) => {
                        // //console.log(item, t)
                        localStorage[`renterFrontPic${t}`] = JSON.stringify(item.renterFrontPic);
                        localStorage[`renterBackPic${t}`] = JSON.stringify(item.renterBackPic);
                        
                        //console.log(localStorage)
                        return (
                            <div key={`row-`+t} style={{borderBottom: '1px solid #eee'}}>
                                <Row gutter={24}>
                                    <Col sm={8}>
                                        <FormItem label="租客姓名">
                                        <Input {...getFieldProps(t + 'renterName', {initialValue: item.renterName,
                                            rules: [{ required: true,  message: '租客姓名不可为空' }]})} />
                                        </FormItem>
                                    </Col>
                                    <Col sm={8}>
                                        <FormItem label="身份证号码">
                                        <Input {...getFieldProps(t + 'renterNo', {initialValue: item.renterNo,
                                            rules: [{ required: true,  message: '身份证号码不可为空' }, {validator: Utils.card}]})} />
                                        </FormItem>
                                    </Col>
                                    <Col sm={8}>
                                        <FormItem label="联系号码">
                                        <Input {...getFieldProps(t + 'renterPhone', {initialValue: item.renterPhone,
                                            rules: [{ required: true,  message: '联系号码不可为空' },
                                            {validator: Utils.phone}]})} />
                                        </FormItem>
                                        {
                                            isDisabled?'':
                                            <a href="javascript:;" onClick={this.deleteOtherRecord.bind(this, t)}><Icon style={{fontSize: 16}} type="minus-circle-o" /></a>
                                        }
                                        
                                    </Col>
                                </Row>
                                <Row gutter={24}>
                                    <Col sm={8}>
                                        <FormItem label="租客性别">
                                        <RadioGroup  {...getFieldProps(t + 'renterSex',{initialValue:item.renterSex})}>
                                            <Radio value="男">男</Radio>
                                            <Radio value="女">女</Radio>
                                        </RadioGroup>
                                        </FormItem>
                                    </Col>
                                    <Col sm={8}>
                                        <FormItem label="联系地址">
                                        <Input {...getFieldProps(t + 'renterAddress',{initialValue:item.renterAddress})} />
                                        </FormItem>
                                    </Col>
                                    <Col sm={8}>
                                        <FormItem label="工作单位">
                                        <Input {...getFieldProps(t + 'renterCompany',{initialValue:item.renterCompany})} />
                                        </FormItem>
                                        
                                    </Col>
                                </Row>
                                <Row gutter={24} className="pic-box">
                                    <Col sm={24} className="img-label-wrap">
                                        <FormItem
                                        label="身份证正面">
                                        <Upload  {...this.getCardProps(this.state[`renterFrontPic${t}`],'card', 'renterFrontPic' + t)} >
                                            {
                                                this.state[`renterFrontPic${t}`].length === 0 ?
                                                <div className="img-icon">
                                                    <Icon type="plus"/>
                                                    <h5>添加</h5>
                                                </div>
                                                :''
                                            }   
                                        </Upload>
                                        </FormItem>
                                    </Col>
                                </Row>
                                <Row gutter={24} className="pic-box">
                                    <Col sm={24} className="img-label-wrap">
                                        <FormItem
                                        label="身份证反面">
                                        <Upload  {...this.getCardProps(this.state[`renterBackPic${t}`],'card', 'renterBackPic'+ t)} >
                                            {
                                                this.state[`renterBackPic${t}`].length === 0 ?
                                                <div className="img-icon">
                                                    <Icon type="plus"/>
                                                    <h5>添加</h5>
                                                </div>
                                                :''
                                            }
                                        </Upload>
                                        </FormItem>
                                    </Col>
                                </Row>
                                                                
                            </div>
                        )
                        
                    })
                }
                {
                    key.map((t, index) => {
                        return (
                            <div key={`row-`+t} style={{borderBottom: '1px solid #eee'}}>
                                <Row gutter={24}>
                                    <Col sm={8}>
                                        <FormItem label="租客姓名">
                                        <Input {...getFieldProps(t + 'renterName', {initialValue: '',
                                            rules: [{ required: true,  message: '租客姓名不可为空' }]})} />
                                        </FormItem>
                                    </Col>
                                    <Col sm={8}>
                                        <FormItem label="身份证号码">
                                        <Input {...getFieldProps(t + 'renterNo', {initialValue: '',
                                            rules: [{ required: true,  message: '身份证号码不可为空' }, {validator: Utils.card}]})} />
                                        </FormItem>
                                    </Col>
                                    <Col sm={8}>
                                        <FormItem label="联系号码">
                                        <Input {...getFieldProps(t + 'renterPhone', {initialValue: '',
                                            rules: [{ required: true,  message: '联系号码不可为空' },
                                            {validator: Utils.phone}]})} />
                                        </FormItem>
                                        {
                                            isDisabled?'':
                                            <a href="javascript:;" onClick={this.deleteRecord.bind(this, t)}><Icon style={{fontSize: 16}} type="minus-circle-o" /></a>
                                        }
                                        
                                    </Col>
                                </Row>
                                <Row gutter={24}>
                                    <Col sm={8}>
                                        <FormItem label="租客性别">
                                        <RadioGroup  {...getFieldProps(t + 'renterSex',{initialValue:'男'})}>
                                            <Radio value="男">男</Radio>
                                            <Radio value="女">女</Radio>
                                        </RadioGroup>
                                        </FormItem>
                                    </Col>
                                    <Col sm={8}>
                                        <FormItem label="联系地址">
                                        <Input {...getFieldProps(t + 'renterAddress')} />
                                        </FormItem>
                                    </Col>
                                    <Col sm={8}>
                                        <FormItem label="工作单位">
                                        <Input {...getFieldProps(t + 'renterCompany')} />
                                        </FormItem>
                                        
                                    </Col>
                                </Row>
                                <Row gutter={24} className="pic-box">
                                    <Col sm={24} className="img-label-wrap">
                                        <FormItem
                                        label="身份证正面">
                                        <Upload  {...this.getCardProps(JSON.parse(localStorage[`renterFrontPic${t}`]),'card', 'renterFrontPic' + t)} >
                                            {
                                                JSON.parse(localStorage[`renterFrontPic${t}`]).length === 0 ?
                                                <div className="img-icon">
                                                    <Icon type="plus"/>
                                                    <h5>添加</h5>
                                                </div>
                                                :''
                                            }   
                                        </Upload>
                                        </FormItem>
                                    </Col>
                                </Row>
                                <Row gutter={24} className="pic-box">
                                    <Col sm={24} className="img-label-wrap">
                                        <FormItem
                                        label="身份证反面">
                                        <Upload  {...this.getCardProps(JSON.parse(localStorage[`renterBackPic${t}`]),'card', 'renterBackPic'+ t)} >
                                            {
                                                JSON.parse(localStorage[`renterBackPic${t}`]).length === 0 ?
                                                <div className="img-icon">
                                                    <Icon type="plus"/>
                                                    <h5>添加</h5>
                                                </div>
                                                :''
                                            }
                                        </Upload>
                                        </FormItem>
                                    </Col>
                                </Row>
                            </div>
                        )

                    })
                }
                    
                </Form>
            </div>
        )
    }
});
BaseInfo = Form.create()(BaseInfo);
export default BaseInfo;